package com.util.img;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * @Description: TODO
 * @Author: hechaobo
 * @Date: 2024/9/6
 **/
public class ImgUtil {
    public static void background() throws IOException {
        // 加载图片
        BufferedImage    image = ImageIO.read(new File("C:\\Users\\11314\\Pictures\\lQLPJxCIouzr5GjNAoDNAeCw18Z71W2zzOkFKaniuECkAA_480_640.jpg"));

// 转换为灰度图像
        BufferedImage grayImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
        Graphics g = grayImage.getGraphics();
        g.drawImage(image, 0, 0, null);
        g.dispose();
        // 设置阈值
        int threshold = 128;

// 二值化图像
        for (int y = 0; y < grayImage.getHeight(); y++) {
            for (int x = 0; x < grayImage.getWidth(); x++) {
                int pixel = grayImage.getRGB(x, y);
                int intensity = (pixel >> 16) & 0xff; // 获取灰度值
                if (intensity < threshold) {
                    grayImage.setRGB(x, y, Color.WHITE.getRGB()); // 将底色设为白色
                }
            }
        }
// 保存图像
        ImageIO.write(grayImage, "jpg", new File("/temp/image.jpg"));

    }

    public static void main(String[] args) throws IOException {
      background();
    }
}
